package com.webserver.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.Locale;

/**
 * 该线程任务负责与指定的客户端完成HTTP交互
 * 每次http交互都采取一问一答得规则，因此交互由三步来完成：
 * 1.解析请求
 * 2.处理请求
 * 3.发送相应
 */
public class ClientHandler implements Runnable{
    private Socket socket;
    public ClientHandler(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            InputStream in = socket.getInputStream();
            StringBuilder builder = new StringBuilder();
            char pre = ' ',cur = ' ';//pre上次读的字符，cur本次读的字符
            int d ;
            while((d = in.read())!=-1){
                cur = (char) d;
                if (pre ==13&& cur==10){
                    break;
                }
                builder.append(cur);
                pre = cur;
            }
            String line =  builder.toString().trim();
            System.out.println(line);
            //请求行的相关信息
            String method;//请求方式
            String uri;//抽象路径
            String protocol;//协议

            String[] m =  line.split(" ");
            method = m[0];
            uri = m[1];
            protocol = m[2];

//            method = line.substring(0,(char)' ');
//            uri =  line.substring((char)' ',(char)' ');
//            protocol = line.substring();
            System.out.println("method:"+method);
            System.out.println("uri:"+uri);
            System.out.println("protoval:"+protocol);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
